
import FileSaver from 'file-saver'
import JSZip from 'jszip'

import { isObject } from '@/utils/common'
import formatCode from '@/utils/formatCode'

/**
 * 导出默认内容
 * fileItem 文件item对象
 * @returns {*}
 */
const outCommonExportFile = (fileItem) => {
  if (fileItem.strCode) {
    return fileItem.strCode
  } else if (isObject(fileItem.fileText)) {
    let codeForRender = fileItem.codeForRender
      .replace(/\s{1}lc_id=".+?"/g, '')
      .replace(/\s{1}lc-mark/g, '')
    return formatCode(codeForRender, 'vue')
  } else {
    return fileItem.fileText
  }
}
const genderOutExportFolder = (fileName, list, customClass = null, commonFileParam, pointer) => {
  pointer = pointer.folder(fileName)
  for (let i = 0; i < list.length; i++) {
    let item = list[i]
    let itemName = item.label
    if (item.type === 'folder') {
      let folderList = item.children
      if (folderList) {
        genderOutExportFolder(itemName, folderList, customClass, commonFileParam, pointer)
      }
    } else {
      let fileText = ''

      fileText = outCommonExportFile(item)
      pointer.file(itemName, fileText)
    }
  }
  return pointer
}

/**
 * 从list 中提供下载，包含文件夹下的文件
 * @param fileName
 * @param list
 */
const outExportFolder = (fileName, list, customClass = null, commonFileParam) => {
  return new Promise((resolve, reject) => {
    let pointer = new JSZip()
    pointer = genderOutExportFolder(fileName, list, customClass, commonFileParam, pointer)
    pointer.root = ''
    pointer
      .generateAsync({
        type: 'blob',
      })
      .then(
        (blob) => {
          console.log('blob:', blob)
          FileSaver.saveAs(blob, `${fileName}.zip`)
          resolve(true)
        },
        (err) => {
          console.log('导出失败了:', err)
          reject(new Error('导出失败了'))
        },
      )
  })
}

export {

  outExportFolder,

  outCommonExportFile,

}
